package com.tencreat.mall.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencreat.common.annotation.Log;
import com.tencreat.common.annotation.RepeatSubmit;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.AjaxResult;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.enums.BusinessType;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.common.utils.poi.ExcelUtil;
import com.tencreat.domain.mall.MallGoods;
import com.tencreat.domain.mall.MallGoodsNorms;
import com.tencreat.domain.mall.dto.*;
import com.tencreat.domain.mall.vo.MallGoodsAllVO;
import com.tencreat.domain.mall.vo.MallSupplierGoodsVO;
import com.tencreat.domain.mall.vo.MallSupplierGoodsQueryVO;
import com.tencreat.service.mall.IMallGoodsNormsService;
import com.tencreat.service.mall.IMallGoodsService;
import com.tencreat.service.mall.IMallSupplierGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 供应商的商品大厅
 * @author zixin
 */
@RestController
@RequestMapping("/mall/supplier-goods")
@Api(tags = "商品大厅-供应商")
public class MallSupplierGoodsController extends BaseController {

    @Autowired
    private IMallGoodsService goodsService;

    @Autowired
    private IMallSupplierGoodsService supplierGoodsService;

    @Autowired
    private IMallGoodsNormsService mallGoodsNormsService;

    @ApiOperation("列表")
    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:list')")
    HttpResult<Page<MallSupplierGoodsVO>> list(@RequestBody @Validated MallSupplierGoodsDTO dto) {
        dto.setUserId(getLoginCheck().getUser().getUserId());
        dto.setAuditStatus(1);
        return HttpResult.ok(supplierGoodsService.list(generatePage(dto), dto));
    }
    @ApiOperation("审核列表")
    @PostMapping("/audit-list")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:audit-list')")
    HttpResult<Page<MallSupplierGoodsVO>> list(@RequestBody @Validated MallSupplierGoodsAuditDTO dto) {
        dto.setUserId(getLoginCheck().getUser().getUserId());
        return HttpResult.ok(supplierGoodsService.listAudit(generatePage(dto), dto));
    }

    @ApiOperation("查询")
    @GetMapping("/query/{id}")
    @PreAuthorize("@ss.hasAnyPermi('mall:supplier-goods:query,mall:supplier-goods:edit')")
    HttpResult<MallGoodsAllVO> query(@PathVariable Long id) {
        return HttpResult.ok(supplierGoodsService.query(id));
    }
    @ApiOperation("查询")
    @GetMapping("/queryAdmin/{id}")
    @PreAuthorize("@ss.hasAnyPermi('mall:supplier-goods:query,mall:supplier-goods:edit')")
    HttpResult<MallSupplierGoodsQueryVO> queryByAdmin(@PathVariable Long id) {
        return HttpResult.ok(supplierGoodsService.queryByAdmin(id));
    }
    @ApiOperation("新增")
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:add')")
    @RepeatSubmit
    @Log(title = "商品管理>商品大厅-供应商", businessType = BusinessType.INSERT)
    HttpResult add(@RequestBody @Validated MallGoodsAddDTO dto) {
        return HttpResult.ok(supplierGoodsService.add(dto));
    }

    @ApiOperation("修改")
    @PostMapping("/edit")
//    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:edit')")
    @RepeatSubmit
    @Log(title = "商品管理>商品大厅-供应商", businessType = BusinessType.UPDATE)
    HttpResult edit(@RequestBody @Validated MallGoodsEditDTO dto) {
        MallGoods goods = dto.getGoods();
        if (goods.getId() == null) {
            return HttpResult.error("数据有误");
        }
        if (dto.getNorms() == null || dto.getNorms().size() < 0) {
            throw new CustomException("规格信息不能为空");
        }
        goods.setIsOnSale(0);
        goods.setAuditStatus(0);
        BigDecimal miniPrice = null;
        BigDecimal inventory = BigDecimal.ZERO;

        List<MallGoodsNorms> norms = dto.getNorms();
        for (MallGoodsNorms goodsNorms : norms) {
            inventory = inventory.add(BigDecimal.valueOf(goodsNorms.getInventory()));
            if (miniPrice == null) {
                miniPrice = goodsNorms.getRetailPrice();
                goods.setSupplyPrice(goodsNorms.getSupplyPrice());
                //goods.setCounterPrice(goodsNorms.getScribingPrice());
                goods.setDeductPrice(goodsNorms.getDeductPrice());
            }
            if (miniPrice.compareTo(goodsNorms.getRetailPrice()) > 0) {
                miniPrice = goodsNorms.getRetailPrice();
                goods.setSupplyPrice(goodsNorms.getSupplyPrice());
                //goods.setCounterPrice(goodsNorms.getScribingPrice());
                goods.setDeductPrice(goodsNorms.getDeductPrice());
            }
            goodsNorms.setGoodsId(goods.getId());
            goodsNorms.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            //goodsNorms.setTenantId(null);
        }
        if (null != miniPrice) {
            goods.setRetailPrice(miniPrice);
        }
       /* if (goods.getMemberDiscount() != null) {
            goods.setSalesDiscount(goods.getMemberDiscount() + "");
        }*/
        goods.setInventory(inventory.longValue());
        goodsService.updateById(goods);
        mallGoodsNormsService.saveOrUpdateBatch(norms);

        return HttpResult.ok();
    }

    @ApiOperation("删除")
    @DeleteMapping("/remove/{id}")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:remove')")
    @Log(title = "商品管理>商品大厅-供应商", businessType = BusinessType.DELETE)
    HttpResult remove(@PathVariable Long id) {
        goodsService.remove(
                new LambdaQueryWrapper<MallGoods>()
                .eq(MallGoods::getId, id)
                .eq(MallGoods::getUserId, getLoginCheck().getUser().getUserId()));
        return HttpResult.ok();
    }

    @ApiOperation("上架")
    @PostMapping("/up")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:up')")
    @Log(title = "商品管理>商品大厅-供应商", businessType = BusinessType.UPDATE)
    HttpResult up(@ApiParam @RequestBody Long[] ids) {
        Long userId = getLoginCheck().getUser().getUserId();
        Arrays.stream(ids).forEach(item -> {
            goodsService.lambdaUpdate()
                    .eq(MallGoods::getId, item)
                    .eq(MallGoods::getAuditStatus, 1)
                    .eq(MallGoods::getUserId, userId)
                    .set(MallGoods::getIsOnSale, 1)
                    .update();
        });
        return HttpResult.ok();
    }

    @ApiOperation("下架")
    @PostMapping("/down")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:down')")
    @Log(title = "商品管理>商品大厅-供应商", businessType = BusinessType.UPDATE)
    HttpResult down(@ApiParam @RequestBody Long[] ids) {
        Long userId = getLoginCheck().getUser().getUserId();
        Arrays.stream(ids).forEach(item -> {
            goodsService.lambdaUpdate()
                    .eq(MallGoods::getId, item)
                    .eq(MallGoods::getAuditStatus, 1)
                    .eq(MallGoods::getUserId, userId)
                    .set(MallGoods::getIsOnSale, 0)
                    .update();
        });
        return HttpResult.ok();
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermi('mall:supplier-goods:export')")
    @Log(title = "商品管理>商品大厅-供应商", businessType = BusinessType.EXPORT)
    @RepeatSubmit
    AjaxResult export(@RequestBody @Validated MallSupplierGoodsDTO dto) {
        dto.setUserId(getLoginCheck().getUser().getUserId());
        dto.setAuditStatus(1);
        List<MallSupplierGoodsVO> list = supplierGoodsService.list(dto);
        dto.setUserId(getLoginCheck().getUser().getUserId());
        ExcelUtil<MallSupplierGoodsVO> util = new ExcelUtil<>(MallSupplierGoodsVO.class);
        return util.exportExcel(list, "ad");
    }

    @ApiOperation("商品数量统计")
    @GetMapping("/queryCount")
    public HttpResult queryCount() {
        return HttpResult.ok(supplierGoodsService.queryCount(getLoginCheck().getUser().getUserId()));
    }

    @ApiOperation("商品审核数量统计")
    @GetMapping("/queryAuditCount")
    public HttpResult queryAuditCount() {
        return HttpResult.ok(supplierGoodsService.queryAuditCount(getLoginCheck().getUser().getUserId()));
    }
}
